package com.chuanghai.light.utils;

import com.chuanghai.light.exceptionhandle.CommonException;
import com.chuanghai.light.exceptionhandle.emum.CommonErrorEmum;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @Author: codingliang
 * @Description: base64 工具类
 * @Date: 2020-06-23 14:30
 * @Version: V1.0
 **/
public class MyBase64Util {

    /**
     *
     * @param base64Data bas64字符串
     * @param localPath 存储地址
     * @return 文件名称
     */
    public static String base64ToImage(String base64Data, String localPath) throws CommonException {
        String dataPrix; // base64格式前头
        String data; // 实体部分数据
        String [] d = base64Data.split("base64,"); // 将字符串分成数组
        if(!(d != null && d.length == 2)){
            throw new CommonException(CommonErrorEmum.OPERATION_FAIL);
        }
        dataPrix = d[0];
        data = d[1];

        String suffix = ""; //图片后缀，用以识别哪种格式数据
        if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){
            // 编码的jpeg图片数据
            suffix = ".jpg";
        }else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){
            //编码的icon图片数据
            suffix = ".ico";
        }else if("data:image/gif;".equalsIgnoreCase(dataPrix)){
            //编码的gif图片数据
            suffix = ".gif";
        }else if("data:image/png;".equalsIgnoreCase(dataPrix)){
            //编码的png图片数据
            suffix = ".png";
        }else {
            throw new CommonException(CommonErrorEmum.OPERATION_FAIL);
        }

        //文件名称
        String fileName = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() + suffix;

        File targetFile = new File(localPath + fileName);
        BASE64Decoder decoder = new BASE64Decoder();
        try(OutputStream out = new FileOutputStream(targetFile)){
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length ; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
        }catch (Exception e){
            throw new CommonException(CommonErrorEmum.FILE_UPLOAD_ERROR);
        }

        return fileName;
    }

}
